package com.kkb.config;

import com.kkb.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;

/**
 * Security配置类
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthenticationProvider provider;  //注入我们自己的AuthenticationProvider


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        /**登录授权*/
        http
                .authorizeRequests().antMatchers("/ajax/**","/img/**","/ruoyi/**","/css/**", "/js/**", "/fonts/**", "/login/**", "/fonts/**").permitAll() //静态资源不被拦截
                .and()
                .authorizeRequests().antMatchers("/regist/**", "/toregist/**","/message.html").permitAll()  //用户注册页面不被拦截
                .and()
                .authorizeRequests().antMatchers("/sms/**").permitAll()  //短信登录请求不被拦截
                .and()
                .authorizeRequests().anyRequest().authenticated()   //其余页面都需要认证（只有登录后才可以正常访问）
                .and()
                .formLogin().loginPage("/tologin")            //表单登录页面
//                .formLogin().loginPage("/message")            //表单登录页面
                .loginProcessingUrl("/login")                 //表单登录方法
                .defaultSuccessUrl("/index")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .and()
                .csrf().disable();


        // 关闭CSRF跨域
        http.csrf().disable();
        /**退出删除cookie*/
        http.logout().deleteCookies("JESSIONID");
            /**解决中文乱码问题*/
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        http.addFilterBefore(filter, CsrfFilter.class);

    }
    /**
     * @Description: 验证身份类
     */

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{

        auth.authenticationProvider(provider);

    }


}
